/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.bean.AdjustBillBean;
import com.minierp.bean.AdjustBillItemBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.AdjustBillDao;
import com.minierp.dao.AdjustBillItemDao;
import com.minierp.dao.BusinessBillDao;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.CooperBillDao;
import com.minierp.dao.DepartmentDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.PayBillDao;
import com.minierp.dao.PurchaseBillDao;
import com.minierp.dao.ReceiveBillDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.err.NotAllowException;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncAdjustBillFormCtrHelper;
import com.minierp.helper.EncCommonHelper;
import com.minierp.model.AdjustBill;
import com.minierp.model.AdjustBillItem;
import com.minierp.model.BusinessBill;
import com.minierp.model.BusinessBillExt;
import com.minierp.model.CodeRule;
import com.minierp.model.CooperBill;
import com.minierp.model.CooperBillExt;
import com.minierp.model.Establishment;
import com.minierp.model.PurchaseBill;
import com.minierp.model.PurchaseBillExt;
import com.minierp.model.TallySet;
import com.minierp.service.AdjustBillService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class AdjustBillFormCtr extends SimpleFormController {
	private DepartmentDao departmentDao;
	private AdjustBillItemDao adjustBillItemDao;
	private AdjustBillDao adjustBillDao;
	private ReceiveBillDao receiveBillDao;
	private BusinessBillDao businessBillDao;
	private PurchaseBillDao purchaseBillDao;
	private CooperBillDao cooperBillDao;
	private PayBillDao payBillDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private IdGenerator idGenerator;
	private AdjustBillService adjustBillService;
	private DataSource dataSource;

	protected Map referenceData(HttpServletRequest request) throws Exception {
		HashMap refData = new HashMap();
		String id = request.getParameter("id");
		if (id == null) {
			id = "";
		}

		refData.put("id", id);
		String retVal = request.getParameter("ret_val");
		if (retVal == null) {
			retVal = "";
		}

		refData.put("retVal", retVal);
		refData.put("departmentList", this.departmentDao.getList(true));
		return refData;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		CodeRule cr = this.codeRuleDao.get("ADJUST_BILL");
		if (cr == null) {
			throw new Exception("Code rule not found for adjust bill");
		} else {
			AdjustBillBean form;
			Establishment est;
			if (id != null && !id.equals("")) {
				AdjustBill arg23 = (AdjustBill) this.adjustBillDao.get(
						AdjustBill.class, Long.parseLong(id));
				if (arg23 == null) {
					throw new Exception("Record not found for id:" + id);
				}

				est = (Establishment) this.adjustBillDao.get(
						Establishment.class, arg23.getClientId());
				TallySet arg24 = (TallySet) this.adjustBillDao.get(
						TallySet.class, arg23.getTallySetId());
				List arg25 = this.adjustBillItemDao.getListByAdjustBill(arg23
						.getId());
				form = EncAdjustBillFormCtrHelper.doFormBackingObjectEdit(cr,
						arg23, est, arg24, arg25);
			} else {
				if (!EncCommonHelper.checkPrivilege(request, "ADJU_BILL")) {
					throw new PermissionDennyException("Permission Denny");
				}

				String dataType = request.getParameter("data_type");
				est = null;
				String adjustType = request.getParameter("adjust_type");
				UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
				long tallySetId = ub.getUser().getDfTsId();
				String relType = "";
				if (!adjustType.equals("PAY_ABATE")
						&& !adjustType.equals("PAY_ADD")
						&& !adjustType.equals("PUR_BACK_ABATE")
						&& !adjustType.equals("PUR_BACK_ADD")) {
					if (!adjustType.equals("COLLECT_ABATE")
							&& !adjustType.equals("COLLECT_ADD")) {
						if (!adjustType.equals("COO_ABATE")
								&& !adjustType.equals("COO_ADD")) {
							throw new Exception("adjust type not support yet.");
						}

						relType = "COOPER_BILL";
					} else {
						relType = "BUSINESS_BILL";
					}
				} else {
					relType = "PURCHASE_BILL";
				}

				Object itemList = new ArrayList();
				if (dataType != null) {
					String clientId;
					if (dataType.equals("BILL")) {
						clientId = request.getParameter("bill_id_str");
						String[] arg26 = clientId.split(";");
						long arg27;
						int arg28;
						if (!adjustType.equals("COLLECT_ABATE")
								&& !adjustType.equals("COLLECT_ADD")) {
							if (!adjustType.equals("PAY_ABATE")
									&& !adjustType.equals("PAY_ADD")
									&& !adjustType.equals("PUR_BACK_ABATE")
									&& !adjustType.equals("PUR_BACK_ADD")) {
								if (!adjustType.equals("COO_ABATE")
										&& !adjustType.equals("COO_ADD")) {
									throw new Exception(
											"adjust type not support yet.");
								}

								arg27 = 0L;

								for (arg28 = 0; arg28 < arg26.length; ++arg28) {
									CooperBill arg31 = (CooperBill) this.adjustBillDao
											.get(CooperBill.class, Long
													.parseLong(arg26[arg28]));
									CooperBillExt arg34 = (CooperBillExt) this.adjustBillDao
											.get(CooperBillExt.class, Long
													.parseLong(arg26[arg28]));
									if (arg31 != null) {
										arg27 = arg31.getCooperatorId();
										((List) itemList).add(this
												.parseItemByCoo(arg31, arg34));
									}
								}

								if (arg27 != 0L) {
									est = (Establishment) this.adjustBillDao
											.get(Establishment.class, arg27);
								}
							} else {
								arg27 = 0L;

								for (arg28 = 0; arg28 < arg26.length; ++arg28) {
									PurchaseBill arg30 = (PurchaseBill) this.adjustBillDao
											.get(PurchaseBill.class, Long
													.parseLong(arg26[arg28]));
									PurchaseBillExt arg33 = (PurchaseBillExt) this.adjustBillDao
											.get(PurchaseBillExt.class, Long
													.parseLong(arg26[arg28]));
									if (arg30 != null) {
										arg27 = arg30.getProviderId();
										((List) itemList).add(this
												.parseItemByPur(arg30, arg33));
									}
								}

								if (arg27 != 0L) {
									est = (Establishment) this.adjustBillDao
											.get(Establishment.class, arg27);
								}
							}
						} else {
							arg27 = 0L;

							for (arg28 = 0; arg28 < arg26.length; ++arg28) {
								BusinessBill arg29 = (BusinessBill) this.businessBillDao
										.get(BusinessBill.class,
												Long.parseLong(arg26[arg28]));
								BusinessBillExt arg32 = (BusinessBillExt) this.businessBillDao
										.get(BusinessBillExt.class,
												Long.parseLong(arg26[arg28]));
								if (arg29 != null) {
									arg27 = arg29.getClientId();
									((List) itemList).add(this.parseItemByBus(
											arg29, arg32));
								}
							}

							if (arg27 != 0L) {
								est = (Establishment) this.adjustBillDao.get(
										Establishment.class, arg27);
							}
						}
					} else if (dataType.equals("EST")) {
						clientId = request.getParameter("est_id");
						est = (Establishment) this.adjustBillDao.get(
								Establishment.class, Long.parseLong(clientId));
						if (!adjustType.equals("COLLECT_ABATE")
								&& !adjustType.equals("COLLECT_ADD")) {
							if (!adjustType.equals("PAY_ABATE")
									&& !adjustType.equals("PAY_ADD")) {
								if (!adjustType.equals("PUR_BACK_ABATE")
										&& !adjustType.equals("PUR_BACK_ADD")) {
									if (!adjustType.equals("COO_ABATE")
											&& !adjustType.equals("COO_ADD")) {
										throw new Exception(
												"adjust type not support yet.");
									}

									itemList = this
											.parseItems(
													this.cooperBillDao.getListForPay(
															Long.parseLong(clientId),
															tallySetId,
															(Date) null,
															(Date) null),
													"COOPER_BILL");
								} else {
									itemList = this.parseItems(
											this.purchaseBillDao.getListForPay(
													Long.parseLong(clientId),
													"BACK", tallySetId,
													(Date) null, (Date) null),
											"PURCHASE_BILL");
								}
							} else {
								itemList = this.parseItems(this.purchaseBillDao
										.getListForPay(
												Long.parseLong(clientId),
												"BUY", tallySetId, (Date) null,
												(Date) null), "PURCHASE_BILL");
							}
						} else {
							itemList = this.parseItems(this.businessBillDao
									.getListForReceive(
											Long.parseLong(clientId),
											tallySetId, (Date) null,
											(Date) null), "BUSINESS_BILL");
						}
					} else if (dataType.equals("ACCOUNT")) {
						clientId = request.getParameter("client_id");
						String startDateStr = request
								.getParameter("start_date");
						String endDateStr = request.getParameter("end_date");
						String linkman = request.getParameter("linkman");
						String type = request.getParameter("type");
						Date startDate = null;
						Date endDate = null;
						SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
						if (startDateStr != null && !startDateStr.equals("")) {
							startDate = sf.parse(startDateStr);
						}

						if (endDateStr != null && !endDateStr.equals("")) {
							endDate = sf.parse(EncCommonHelper.getNextDateStr(
									endDateStr, "yyyy-MM-dd"));
						}

						List bbList = this.businessBillDao
								.getListForAccountRec(Long.parseLong(clientId),
										startDate, endDate, linkman,
										tallySetId, type);

						for (int i = 0; i < bbList.size(); ++i) {
							Object[] bo = (Object[]) bbList.get(i);
							((List) itemList).add(this.parseItemByBus(
									(BusinessBill) bo[0],
									(BusinessBillExt) bo[1]));
						}

						est = (Establishment) this.receiveBillDao.get(
								Establishment.class, Long.parseLong(clientId));
					}
				}

				form = EncAdjustBillFormCtrHelper.doFormBackingObjectNew(
						request, adjustType, relType, cr, est, (List) itemList);
			}

			return form;
		}
	}

	private List<AdjustBillItemBean> parseItems(List billList, String billType)
			throws Exception {
		ArrayList arr = new ArrayList();
		if (billList != null) {
			for (int i = 0; i < billList.size(); ++i) {
				AdjustBillItemBean bean;
				Object[] bo;
				if (billType.equals("BUSINESS_BILL")) {
					bo = (Object[]) billList.get(i);
					bean = this.parseItemByBus((BusinessBill) bo[0],
							(BusinessBillExt) bo[1]);
				} else if (billType.equals("PURCHASE_BILL")) {
					bo = (Object[]) billList.get(i);
					bean = this.parseItemByPur((PurchaseBill) bo[0],
							(PurchaseBillExt) bo[1]);
				} else {
					if (!billType.equals("COOPER_BILL")) {
						throw new Exception("bill type not supported!");
					}

					bo = (Object[]) billList.get(i);
					bean = this.parseItemByCoo((CooperBill) bo[0],
							(CooperBillExt) bo[1]);
				}

				bean.setThisCostStr("0");
				bean.getAdjustBillItem().setThisCost(new BigDecimal(0));
				arr.add(bean);
			}
		}

		return arr;
	}

	private AdjustBillItemBean parseItemByBus(BusinessBill b, BusinessBillExt be) {
		AdjustBillItemBean cb = new AdjustBillItemBean();
		AdjustBillItem c = new AdjustBillItem();
		cb.setAdjustBillItem(c);
		cb.setStatus("NEW");
		c.setBusinessBillCode(b.getBillCode());
		c.setBusinessBillId(b.getId());
		c.setContent(b.getContent());
		c.setOrderDate(b.getOrderDate());
		c.setRemainCost(b.getCost().add(be.getAdjustCost())
				.subtract(be.getCollectedCost()));
		c.setThisCost(c.getRemainCost());
		c.setTotalCost(b.getCost());
		cb.setThisCostStr(EncCommonHelper.parseBigDecimal(c.getThisCost()));
		return cb;
	}

	private AdjustBillItemBean parseItemByPur(PurchaseBill b, PurchaseBillExt be) {
		AdjustBillItemBean cb = new AdjustBillItemBean();
		AdjustBillItem c = new AdjustBillItem();
		cb.setAdjustBillItem(c);
		cb.setStatus("NEW");
		c.setBusinessBillCode(b.getBillCode());
		c.setContent(b.getContent());
		c.setBusinessBillId(b.getId());
		c.setOrderDate(b.getPurchaseDate());
		c.setRemainCost(b.getCost().add(be.getAdjustCost())
				.subtract(be.getPaiedCost()));
		c.setThisCost(c.getRemainCost());
		c.setTotalCost(b.getCost());
		cb.setThisCostStr(EncCommonHelper.parseBigDecimal(c.getThisCost()));
		return cb;
	}

	private AdjustBillItemBean parseItemByCoo(CooperBill b, CooperBillExt be) {
		AdjustBillItemBean cb = new AdjustBillItemBean();
		AdjustBillItem c = new AdjustBillItem();
		cb.setAdjustBillItem(c);
		cb.setStatus("NEW");
		c.setBusinessBillCode(b.getBillCode());
		c.setContent(b.getContent());
		c.setBusinessBillId(b.getId());
		c.setOrderDate(b.getCooperDate());
		c.setRemainCost(b.getCost().add(be.getAdjustCost())
				.subtract(be.getPaiedCost()));
		c.setThisCost(c.getRemainCost());
		c.setTotalCost(b.getCost());
		cb.setThisCostStr(EncCommonHelper.parseBigDecimal(c.getThisCost()));
		return cb;
	}

	protected void onBind(HttpServletRequest request, Object command)
			throws Exception {
		AdjustBillBean form = (AdjustBillBean) command;
		EncAdjustBillFormCtrHelper.doOnBind(form, request, this.dataSource);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		String id = request.getParameter("id");
		String examine = request.getParameter("examine");
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		AdjustBillBean form = (AdjustBillBean) command;
		AdjustBill obj = form.getAdjustBill();
		if (examine != null && examine.equals("1")) {
			if (!EncCommonHelper.checkPrivilege(request, "ADJU_EXAM")) {
				throw new Exception("Permission deny!");
			}

			obj.setExamined("Y");
			if (ub.getStaffer() != null) {
				obj.setExaminerId(ub.getStaffer().getId());
				obj.setExaminerName(ub.getStaffer().getStafferName());
			}
		} else {
			obj.setExamined("N");
		}

		if (id != null && !id.equals("")) {
			if (!EncCommonHelper.checkPrivilege(request, "ADJU_BILL")) {
				throw new Exception("Permission deny!");
			}

			try {
				this.adjustBillService.txUpdate(form, this.adjustBillDao,
						this.adjustBillItemDao, this.idGenerator,
						this.receiveBillDao, this.payBillDao,
						this.businessBillDao);
			} catch (CannotAcquireLockException arg13) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg14) {
				EncCommonHelper.setAlertMessage(request, arg14.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		} else {
			try {
				this.adjustBillService.txInsert(form, this.adjustBillDao,
						this.adjustBillItemDao, this.serialNumberDao,
						this.idGenerator, this.receiveBillDao, this.payBillDao,
						this.businessBillDao);
			} catch (CannotAcquireLockException arg15) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg16) {
				EncCommonHelper.setAlertMessage(request, arg16.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		}

		String continueFlag = request.getParameter("continue_flag");
		String printFlag = request.getParameter("print_flag");
		String alertType = request.getParameter("alert_type");
		if (continueFlag != null && continueFlag.equals("NEW")) {
			EncCommonHelper.setAlertMessage(request, "调账单保存成功！");
			mv = new ModelAndView(
					"redirect:/finance/AdjustBillNew.ihtm?ret_val=1&alert_type="
							+ alertType + "&adjust_type=" + obj.getAdjustType());
		} else if (printFlag != null && printFlag.equals("SHOW")) {
			mv = new ModelAndView("redirect:/finance/AdjustBillPrint.ihtm?id="
					+ obj.getId());
		} else {
			if (alertType == null || !alertType.equals("NONE")) {
				EncCommonHelper.setAlertMessage(request, "调账单保存成功！");
			}

			if (printFlag != null && printFlag.equals("CALLBACK")) {
				mv.addObject("returnValue", String.valueOf(obj.getId()) + ";Y");
			} else {
				mv.addObject("returnValue", String.valueOf(obj.getId()));
			}
		}

		mv.addObject("alertType", alertType);
		return mv;
	}

	public BusinessBillDao getBusinessBillDao() {
		return this.businessBillDao;
	}

	public void setBusinessBillDao(BusinessBillDao businessBillDao) {
		this.businessBillDao = businessBillDao;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public DepartmentDao getDepartmentDao() {
		return this.departmentDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public AdjustBillDao getAdjustBillDao() {
		return this.adjustBillDao;
	}

	public void setAdjustBillDao(AdjustBillDao adjustBillDao) {
		this.adjustBillDao = adjustBillDao;
	}

	public AdjustBillItemDao getAdjustBillItemDao() {
		return this.adjustBillItemDao;
	}

	public void setAdjustBillItemDao(AdjustBillItemDao adjustBillItemDao) {
		this.adjustBillItemDao = adjustBillItemDao;
	}

	public AdjustBillService getAdjustBillService() {
		return this.adjustBillService;
	}

	public void setAdjustBillService(AdjustBillService adjustBillService) {
		this.adjustBillService = adjustBillService;
	}

	public ReceiveBillDao getReceiveBillDao() {
		return this.receiveBillDao;
	}

	public void setReceiveBillDao(ReceiveBillDao receiveBillDao) {
		this.receiveBillDao = receiveBillDao;
	}

	public DataSource getDataSource() {
		return this.dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public PayBillDao getPayBillDao() {
		return this.payBillDao;
	}

	public void setPayBillDao(PayBillDao payBillDao) {
		this.payBillDao = payBillDao;
	}

	public PurchaseBillDao getPurchaseBillDao() {
		return this.purchaseBillDao;
	}

	public void setPurchaseBillDao(PurchaseBillDao purchaseBillDao) {
		this.purchaseBillDao = purchaseBillDao;
	}

	public CooperBillDao getCooperBillDao() {
		return this.cooperBillDao;
	}

	public void setCooperBillDao(CooperBillDao cooperBillDao) {
		this.cooperBillDao = cooperBillDao;
	}
}